package com.dense.kuiniu.bookborrow.business.home.query;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.LanguageUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.dense.kuiniu.bookborrow.R;
import com.dense.kuiniu.bookborrow.base.BaseFragment;
import com.dense.kuiniu.bookborrow.base.SpKey;
import com.dense.kuiniu.bookborrow.base.Url;
import com.dense.kuiniu.bookborrow.business.adapter.BookSearchAdapter;
import com.dense.kuiniu.bookborrow.business.entity.Book;
import com.dense.kuiniu.bookborrow.business.entity.PageList;
import com.dense.kuiniu.bookborrow.view.SpaceItemDecoration;
import com.rxjava.rxlife.RxLife;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import rxhttp.RxHttp;

/**
 * @author Administrator
 * @date 2020/8/7
 */
public class QueryListDelegate extends BaseFragment {
    public static QueryListDelegate getInstance(String key) {
        Bundle bundle = new Bundle();
        bundle.putString("key", key);
        QueryListDelegate delegate = new QueryListDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    private static final int PAGE_SIZE = 10;
    private int mCurrentPage = 1;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.et_search)
    EditText mEtSearch;
    @BindView(R.id.tv_search_result)
    TextView mTvSearchResult;
    private String mSearchKey;
    private BookSearchAdapter mBookSearchAdapter;
    private boolean isSearching = false;
    private boolean hasInit = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mSearchKey = bundle.getString("key");
        }
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.delegate_query_list;
    }

    @OnClick({R.id.tv_search, R.id.tv_return})
    public void onClick(View view) {
        super.onClick(view);
    }

    @Override
    protected void onClick2(View view) {
        int id = view.getId();
        if (id == R.id.tv_search) {
            search(mEtSearch.getText().toString());
        } else if (id == R.id.tv_return) {
            pop();
        }
    }

    @Override
    protected void init() {
        if (getActivity() != null) {
            mTvTitle.setText(getActivity().getResources().getString(R.string.text_query_list));
            mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
            mRecyclerView.addItemDecoration(new SpaceItemDecoration(20));
            mBookSearchAdapter = new BookSearchAdapter(R.layout.item_book_search, null);
            mRecyclerView.setAdapter(mBookSearchAdapter);
            //  mBookSearchAdapter.getLoadMoreModule().setLoadMoreView(new CustomLoadMoreView());
            mBookSearchAdapter.setEmptyView(R.layout.view_loading);
            mBookSearchAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    Book book = (Book) adapter.getItem(position);
                    if (book != null) {
                        start(BookDetailDelegate.getInstance(book));
                    }
                }
            });
            mBookSearchAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore() {
                    isSearching = true;
                    queryBook(false);
                }
            });


            mTvSearchResult.setText(String.format("%s0%s", getString(R.string.text_search_result_count),
                    getString(R.string.text_unit_strip)));
            mEtSearch.setText(mSearchKey);

        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (!hasInit) {
            hasInit = true;
            search(mSearchKey);
        }
    }

    private void search(String searchKey) {
        if (!isSearching) {
            isSearching = true;
            mCurrentPage = 1;
            mSearchKey = searchKey;
            mBookSearchAdapter.getLoadMoreModule().setAutoLoadMore(true);
            mBookSearchAdapter.getLoadMoreModule().setEnableLoadMoreEndClick(false);
            mBookSearchAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
            mBookSearchAdapter.setEmptyView(R.layout.view_loading);
            queryBook(true);
        }
    }

    private void queryBook(boolean isRefresh) {
        RxHttp.get(Url.queryBookList)
                .add("libraryCode", SPUtils.getInstance().getString(SpKey.KEY_BINDING_LIBRARY, "00"))
                .add("searchKey", mSearchKey)
                .add("searchType", 1)
                .add("pageSize", PAGE_SIZE)
                .add("currentPage", mCurrentPage)
                .asResponsePageList(Book.class)
                .to(RxLife.toMain(this))  //感知生命周期，并在主线程回调
                .subscribe(pageList -> {
                    mBookSearchAdapter.setEmptyView(R.layout.view_empty);
                    mCurrentPage++;
                    List<Book> list = pageList.getList();
                    if (mBookSearchAdapter != null) {
                        if (isRefresh) {
                            mBookSearchAdapter.setNewInstance(list);
                            if (list == null || list.size() < PAGE_SIZE) {
                                mBookSearchAdapter.getLoadMoreModule().setEnableLoadMore(false);
                            }
                        } else {
                            if (list != null) {
                                mBookSearchAdapter.addData(list);
                                if (list.size() < PAGE_SIZE) {
                                    mBookSearchAdapter.getLoadMoreModule().loadMoreEnd();
                                } else {
                                    mBookSearchAdapter.getLoadMoreModule().loadMoreComplete();
                                }
                            } else {
                                mBookSearchAdapter.getLoadMoreModule().loadMoreEnd();
                            }
                        }
                    }
                    PageList.Page page = pageList.getPagination();
                    if (page != null) {
                        mTvSearchResult.setText(String.format(LanguageUtils.getCurrentLocale(),
                                "%s%d%s", getString(R.string.text_search_result_count),
                                page.getTotal(), getString(R.string.text_unit_strip)));
                    }
                    isSearching = false;
                }, throwable -> {

                    mTvSearchResult.setText(String.format(LanguageUtils.getCurrentLocale(),
                            "%s%d%s", getString(R.string.text_search_result_count),
                            mBookSearchAdapter.getData().size(), getString(R.string.text_unit_strip)));
                    mBookSearchAdapter.getLoadMoreModule().loadMoreComplete();
                    mBookSearchAdapter.setEmptyView(R.layout.view_empty);
                    isSearching = false;
                });
    }
}